VFG.WebSocket = function(options) {
	this.ws;
	this.lockReconnect = false;
	this.options = options;
	this.url = options.ws;
	let _this=this;
	this.heartCheck = {
        timeout: 60000,
        timeoutObj: null,
        reset: function(){
            clearTimeout(this.timeoutObj);
            return this;
        },
        start: function(){
            this.timeoutObj = setTimeout(function(){
            	_this.ws.send("HeartBeat");
            }, this.timeout)
        }
    }
}

VFG.WebSocket.prototype.createWebSocket=function() {
	let _this=this;
    try {
    	_this.ws = new WebSocket(_this.url);
    	_this.initEventHandle();
    } catch (e) {
    	_this.reconnect();
    }     
}

VFG.WebSocket.prototype.initEventHandle=function() {
	let _this=this;
	_this.ws.onclose = function () {
		_this.reconnect();
    };
    _this. ws.onerror = function () {
    	_this.reconnect();
    };
    _this.ws.onopen = function () {
    	_this.heartCheck.reset().start();
    };
    _this.ws.onmessage = function (event) {
    	if('HeartBeat'!=event.data){
    		if(_this.options.callback){
    			_this.options.callback(event.data);
    		}
    	}
    	_this.heartCheck.reset().start();
    }
}

VFG.WebSocket.prototype.reconnect=function() {
	let _this=this;
    if(_this.lockReconnect) return;
    _this.lockReconnect = true;
    setTimeout(function () {
    	_this.createWebSocket();
    	_this.lockReconnect = false;
    }, 2000);
}

VFG.WebSocket.prototype.destroy = function() {
	var _self = this;
	return Cesium.destroyObject(this);
};
